import pandas as pd
import numpy as np
import os
import datetime
import random
import dir_op
from docx import Document
import re

class planop(object):
    def __init__(self):
        pass
    
    # 获取开始时间
    def start_time(self,a, b):
        c = b.split('-')
        temp1 = int(c[0].split(':')[0])
        temp2 = int(c[0].split(':')[1])
        temptime = datetime.datetime(a.year, a.month, a.day, temp1, temp2, 0)
        return temptime
    
    # 获取结束时间
    def stop_time(self,a, b):
        c = b.split('-')
        temptime = datetime.datetime(1900, 1, 1, 0, 0, 0)
        # p1= b.find('日')
        if '日' in b:
            if '月' in b:
                k = c[1].find('月')
                k1 = c[1].find('日')
                tp = c[1][k1+1:]
                temp1 = int(tp.split(':')[0])  # 小时
                temp2 = int(tp.split(':')[1])  # 分钟
                tp1 = int(c[1][0:k])  # 月
                tp2 = int(c[1][k+1:k1])  # 日
                temptime = datetime.datetime(a.year, tp1, tp2, temp1, temp2, 0)
            else:
                k = c[1].find('日')
                tp = c[1][k+1:]
                tp1 = int(c[1][0:k])  # 日
                temp1 = int(tp.split(':')[0])  # 小时
                temp2 = int(tp.split(':')[1])  # 分钟
                temptime = datetime.datetime(a.year, a.month, tp1, temp1, temp2, 0)
        else:
            temp1 = int(c[1].split(':')[0])
            temp2 = int(c[1].split(':')[1])
            temptime = datetime.datetime(a.year, a.month, a.day, temp1, temp2, 0)
        return temptime
    
    # 获取停电天数
    def get_blackout_day(self,a,b):
        k = b.day-a.day+1
        return k
    
    #导入月计划
    def m_plan_input(self,f_path,sh_name):
        # df = pd.DataFrame()
        df = pd.read_excel(f_path, sheet_name=sh_name)
        pre_col = df.columns
        la_col = ['月计划编号', '申请单位', '工作地点', '设备类型', '设备名称', '主要工作内容', '停役日期',
                '复役日期', '停电天数', '电压', '施工单位', '检修性质', '项目负责人', '备注及说明','计划来源']
        re_name = {}
        for i, j in enumerate(pre_col):
            re_name[j] = la_col[i]
        df.rename(columns=re_name, inplace=True)
        df['月计划编号'] = df['月计划编号'].astype(str)
        x = 'chushizhi'
        Ttemp = datetime.datetime.now()
        # k = Ttemp.hour*100+Ttemp.minute
        
        for i in range(0, df.shape[0]):
            temp = df.iloc[i, 6].strftime('%Y%m%d')
            if x != temp:
                x = temp
                k = random.randint(1,9999)
                y = 'YJH'+x+str('%04d' % k)
                df.iloc[i, 0] = y
            else:
                k = random.randint(1, 9999)
                y = 'YJH'+x+str('%04d' % k)
                df.iloc[i, 0] = y
        
        df['计划执行情况'] = np.nan
        return df

    #导入周计划
    def w_plan_input(self,f_path,sh_name):
        df = pd.read_excel(f_path, sheet_name=sh_name, keep_default_na=False)
        df.drop(index=df[df['厂、站名称'] == ''].index, inplace=True)
        pre_cols = df.columns
        la_cols = ['停役日期', '停复役时间', '厂站名称', '主要工作内容',
                   '申请单位', '备注', '申请单编号', '许可及调度单位','计划来源']
        re_name = {}
        for i, j in enumerate(pre_cols):
            re_name[j] = la_cols[i]
        df.rename(columns=re_name, inplace=True)
        df.insert(0, '周计划编号', np.nan)
        x = 'chushizhi'
        Ttemp = datetime.datetime.now()
        # k = Ttemp.hour*100+Ttemp.minute
        for i in range(0, df.shape[0]):
            temp = df.iloc[i, 1].strftime('%Y%m%d')
            if x != temp:
                x = temp
                k = random.randint(1, 9999)
                y = 'ZJH'+x+str('%04d' % k)
                df.iloc[i, 0] = y
            else:
                k = random.randint(1, 9999)
                y = 'ZJH'+x+str('%04d' % k)
                df.iloc[i, 0] = y
        df.insert(1, '计划停役时间', np.nan)
        df.insert(2, '计划复役时间', np.nan)
        df['计划停役时间'] = df.apply(lambda x: self.start_time(
            x['停役日期'], x['停复役时间']), axis=1)
        df['计划复役时间'] = df.apply(lambda x: self.stop_time(
            x['停役日期'], x['停复役时间']), axis=1)
        df.drop(columns=['停役日期', '停复役时间'],axis=0,inplace = True)
        df['计划执行情况'] = np.nan
        df['月计划编号'] =np.nan
        return df
    
    
    # 导入生产信息日报内容，获取当日工作相关内容
    def daily_input(self,dir_path):
        file_paths = []
        dir_op.getfiles(dir_path, file_paths)
        col_name = ['日期', '编号','序号', '工作地点', '工作内容', '工作单位',
                    '工作负责人', '工作计划时间', '停役开始时间', '复役结束时间', '备注']
        df = pd.DataFrame(columns=col_name)
        pa = re.compile(r'\d{8}')
        i = 0
        for f_path in file_paths:
            f = pa.search(f_path)
            f_doc = Document(f_path)
            Ttable = f_doc.tables[3]
            for row in Ttable.rows:
                temp = [np.nan for j in range(0, 11)]
                temp[0] = datetime.datetime.strptime(f.group(0), '%Y%m%d')
                k = random.randint(1, 999)
                temp[1] = 'GZ'+f.group(0)+str('%04d' % k)
                for j, cell in enumerate(row.cells):
                    temp[j+2] = str(cell.text)
                df.loc[i] = temp
                i = i+1
        df['周计划编号'] = np.nan
        df.drop(index=df[df['序号'] == '序号'].index, inplace=True)
        return df
    
    
        
        
        
        
